<!-- 修改头像 -->
<template>
  <div class="avatar-container">
    <BackgroundBox>
      <uploadAvatar @click="getAvatar" ref="avatarDomRef"></uploadAvatar>
      <div class="but">
        <el-button type="primary" @click="headleUpdata">修改头像</el-button>
      </div>
    </BackgroundBox>
  </div>
</template>

<script setup>
import BackgroundBox from "@/components/BackgroundBox/index.vue";
import uploadAvatar from "@/components/uploadAvatar/index.vue";
import { updateAvatar } from "@/api/user.js";
import { useUserStore } from "@/store/useUserStore.js";
import { storeToRefs } from "pinia";
import { ref } from "vue";
const { readUserInfo } = storeToRefs(useUserStore());
const {getUserInfo} = useUserStore()
const avatarRef = ref();
const avatarDomRef = ref();
const getAvatar = (file) => {
  avatarRef.value = file;
};

const headleUpdata = async () => {
  ElMessageBox.confirm("确定修改吗?", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
  }).then(async () => {
    const { data } = await updateAvatar({
      oldAvatar: readUserInfo.value.avatar,
      newAvatar: avatarRef.value,
    });
    if (data) {
      ElMessage({
        message: "修改成功",
        type: "success",
      });
      avatarDomRef.value.cleanUp();
      avatarRef.value = "";
      await getUserInfo();
    }
  });
  
};
</script>

<style lang="less" scoped>
.avatar-container {
  width: 100%;
  margin: 20px 0;
  .back-container {
    padding: 20px;
  }
  .uploadAvatar-container {
    width: 150px;
    height: 150px;
  }
  .but {
    margin-top: 30px;
  }
}
</style>